#include "widget.h"
#include "ui_widget.h"


#include <QFileDialog>
#include <QDebug>
#include <QColor>
#include <QMessageBox>
#include <QShortcut>


Widget::Widget(QWidget *parent)
        : QWidget(parent), ui(new Ui::Widget) {
    ui->setupUi(this);

    QShortcut *shortcutOpen = new QShortcut(QKeySequence(tr("Ctrl+O","File|Open")),this);
    QShortcut *shorctutSave = new QShortcut(QKeySequence(tr("Ctrl+S","File|Open")),this);
    QShortcut *shorctutZoomIn = new QShortcut(QKeySequence(tr("Ctrl+Shift+=","File|Open")),this);
    QShortcut *shorctutZoomOut = new QShortcut(QKeySequence(tr("Ctrl+Shift+-","File|Open")),this);

    connect(shortcutOpen,&QShortcut::activated,[this](){
        on_btnOpen_clicked();
    });

    connect(shorctutSave,&QShortcut::activated,[this](){
        on_btnSave_clicked();
    });

    connect(shorctutZoomIn,&QShortcut::activated,[this](){
        zoomIn();
    });

    connect(shorctutZoomOut,&QShortcut::activated,[this](){
        zoomOut();
    });


    //下面这行代码可以使得UI随窗口大小改变而改变
    this->setLayout(ui->verticalLayout);
    ui->widgetBottom->setLayout(ui->horizontalLayout);

    connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onCurrentIndexChanged(int)));

    connect(ui->textEdit, SIGNAL(cursorPositionChanged()), this, SLOT(onCcursorPositionChanged()));
}

Widget::~Widget() {
    delete ui;

}

//打开文件
void Widget::on_btnOpen_clicked() {
    //弹出文件选择对话框，默认路径是..，只显示.txt
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                    "E:/Leam/QT", tr("Text(*.txt)"));
    ui->textEdit->clear();

    //设置要操作的文件路径
    file.setFileName(fileName);
    //以只读模式和文本模式
    if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) {
        qDebug() << "file open error";
    }

    this->setWindowTitle(fileName + "Notepad");

    //用于按行读取文本文件
    QTextStream in(&file);
    //设置编码格式防止乱码
//    in.setCodec("UTF-8");
    auto encoding = QStringConverter::encodingForName(ui->comboBox->currentText().toUtf8());
    if (encoding) {
        in.setEncoding(*encoding);
    } else {
        in.setEncoding(QStringConverter::Utf8); // 默认使用UTF-8
    }
    //循环读取文件内容，直到文件末尾
    while (!in.atEnd()) {
        //逐行读取文件内容
        QString context = in.readLine();
//        //输出内容到调试窗口
//        qDebug() << qPrintable(context);
//        //打印到空间输出,会产生覆盖问题
//        ui->textEdit->setText(context);
        ui->textEdit->append(context);
    }

}

//保存文件
void Widget::on_btnSave_clicked() {
    if (!file.isOpen()) {
        //弹出文件对话框，允许用户选择.txt .doc 文件
        QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                                                        "E:/Leam/QT/test.txt",
                                                        tr("Text(*.txt *.doc)"));

        file.setFileName(fileName);
        //以只写模式和文本模式打开文件
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            qDebug() << "file open error";
        }

        this->setWindowTitle(fileName + "Notepad");
    }
    //写入文本
    QTextStream out(&file);
    //设置写入格式
    // out.setEncoding(ui->comboBox->currentText().toStdString().c_str());
    out.setEncoding(QStringConverter::Utf8); // 默认使用UTF-8
    //获取纯文本内容
    QString context = ui->textEdit->toPlainText();
    //写入文件并关闭文件
    out << context;
}

//关闭文件
void Widget::on_btnClose_clicked() {
    ui->textEdit->clear();
    QMessageBox msgBox;

    int ret = QMessageBox::warning(this, tr("你确定要关闭吗"),
                                   tr("当前数据未保存，请问是否要保存.\n"
                                      "Do you want to save your changes?"),
                                   QMessageBox::Save | QMessageBox::Discard
                                   | QMessageBox::Cancel,
                                   QMessageBox::Save);
    switch(ret){
        case QMessageBox::Save://保存
                on_btnSave_clicked();
            qDebug() << "QMessageBox::Save";
            break;
        case QMessageBox::Discard:  //丢弃
            ui->textEdit->clear();
            if(file.isOpen()){
                file.close();
                this->setWindowTitle("Notepad");
            }
            qDebug() << "QMessageBox::Discard";
            break;
        case QMessageBox::Cancel:
            qDebug() << "QMessageBox::Cancel";
            break;
    }
}


//下拉框选项
void Widget::onCurrentIndexChanged(int index) {
    // 清空文本编辑框内容,textEdit文本编辑
    ui->textEdit->clear();
    // 检查文件是否已打开
    if (file.isOpen()) {
        // 创建文件读取流
        QTextStream in(&file);

        // 设置文件编码格式（根据下拉框当前选中的文本）
        auto encoding = QStringConverter::encodingForName(ui->comboBox->currentText().toUtf8());
        if (encoding.has_value()) {
            in.setEncoding(encoding.value());
        } else {
            in.setEncoding(QStringConverter::Utf8); // 默认回退到UTF-
            qWarning() << "Unsupported encoding:" << ui->comboBox->currentText() << ", using UTF-8 instead";
        }
        // 将文件指针重置到文件开头
        file.seek(0);
        // 逐行读取文件内容直到文件末尾
        while (!in.atEnd()) {
            // 读取一行文本
            QString context = in.readLine();
            // 将读取的内容追加到文本编辑框
            ui->textEdit->append(context);
        }
    }
}

//设置行列
void Widget::onCcursorPositionChanged() {
    QTextCursor cursor = ui->textEdit->textCursor();
//   qDebug() << cursor.blockNumber()+1 << ","<< cursor.columnNumber() + 1;
    QString blockNum = QString::number(cursor.blockNumber() + 1);
    QString columnNum = QString::number(cursor.columnNumber() + 1);
    const QString labelMes = "第" + blockNum + "行" + "第" + columnNum + "列" + "  ";
    ui->labelPosition->setText(labelMes);

    //设置当前行高亮
    QList<QTextEdit::ExtraSelection> extraSelection;
    QTextEdit::ExtraSelection ext;
    //1.知道当前行
    ext.cursor = cursor;

    QBrush qBrush(Qt::lightGray);
    //2.颜色
    ext.format.setBackground(qBrush);
    //配置段属性：整行显示，没有这句话不行
    ext.format.setProperty(QTextFormat::FullWidthSelection, true);
    ext.format.setFontUnderline(true);
    //3.设置
    //吧est加到est容器中
    extraSelection.append(ext);
    ui->textEdit->setExtraSelections(extraSelection);

}

void Widget::zoomOut() {
    //获得当前字体信息
    QFont font = ui->textEdit->font();
    //获得当前字体的大小
    int fontSize = font.pointSize();
    if(fontSize == -1) return;
    //改变大小，并设置字体大小
    int newFontSize = fontSize-1;
    font.setPointSize(newFontSize);
    ui->textEdit->setFont(font);
}

void Widget::zoomIn() {
//获得当前字体信息
    QFont font = ui->textEdit->font();
    //获得当前字体的大小
    int fontSize = font.pointSize();
    if(fontSize == -1) return;
    //改变大小，并设置字体大小
    int newFontSize = fontSize+1;
    font.setPointSize(newFontSize);
    ui->textEdit->setFont(font);
}
